"""
状态查询API v2 - 系统状态和更新状态查询
"""

import logging
from flask import Blueprint

from ..middleware import ResponseFormatter
from ..services.image_update_status import get_status_manager
from ..services.integrations import DockerService, ConfigService


logger = logging.getLogger(__name__)
status_bp = Blueprint('status_v2', __name__, url_prefix='/api/v2/status')


@status_bp.route('/update-progress', methods=['GET'])
def get_update_progress():
    """获取当前更新进度"""
    try:
        status_manager = get_status_manager()
        
        # 获取当前状态
        current_status = status_manager.get_current_status()
        
        return ResponseFormatter.success(
            message="更新状态获取成功",
            data=current_status
        )
        
    except Exception as e:
        logger.error(f"获取更新进度失败: {e}")
        return ResponseFormatter.error(
            message=f"获取更新进度失败: {str(e)}",
            error_code="GET_PROGRESS_ERROR"
        )


@status_bp.route('/system-info', methods=['GET'])
def get_system_info():
    """获取系统信息"""
    try:
        docker_service = DockerService()
        
        # 获取运行中的容器
        running_containers = docker_service.list_running_containers()
        
        # 获取当前学校信息
        config_service = ConfigService()
        current_school = config_service.get_current_school_info()
        
        system_info = {
            "running_containers": [
                {
                    "name": container.name,
                    "image": container.image,
                    "status": container.status.value,
                    "ports": container.ports
                }
                for container in running_containers
            ],
            "container_count": len(running_containers),
            "current_school": current_school,
            "system_status": "running" if running_containers else "idle"
        }
        
        return ResponseFormatter.success(
            message="系统信息获取成功",
            data=system_info
        )
        
    except Exception as e:
        logger.error(f"获取系统信息失败: {e}")
        return ResponseFormatter.error(
            message=f"获取系统信息失败: {str(e)}",
            error_code="GET_SYSTEM_INFO_ERROR"
        )


@status_bp.route('/container/<container_name>', methods=['GET'])
def get_container_status(container_name: str):
    """获取指定容器的状态"""
    try:
        docker_service = DockerService()
        
        # 获取容器信息
        container_info = docker_service.get_container_info(container_name)
        
        if not container_info:
            return ResponseFormatter.error(
                message=f"容器不存在: {container_name}",
                error_code="CONTAINER_NOT_FOUND",
                status_code=404
            )
        
        # 获取容器日志（最近100行）
        logs_result = docker_service.get_container_logs(container_name, lines=100)
        
        container_data = {
            "container_info": {
                "id": container_info.id,
                "name": container_info.name,
                "image": container_info.image,
                "status": container_info.status.value,
                "created_at": container_info.created_at,
                "ports": container_info.ports
            },
            "logs": logs_result.details.get('logs', '') if logs_result.success else '',
            "log_errors": logs_result.details.get('errors', '') if logs_result.success else ''
        }
        
        return ResponseFormatter.success(
            message=f"容器状态获取成功: {container_name}",
            data=container_data
        )
        
    except Exception as e:
        logger.error(f"获取容器状态失败: {e}")
        return ResponseFormatter.error(
            message=f"获取容器状态失败: {str(e)}",
            error_code="GET_CONTAINER_STATUS_ERROR"
        )


@status_bp.route('/health', methods=['GET'])
def health_check():
    """健康检查端点"""
    try:
        # 简单的健康检查
        health_status = {
            "status": "healthy",
            "timestamp": "2024-01-01T00:00:00",
            "version": "2.0.0",
            "services": {
                "api": "online",
                "docker": "online",
                "config": "online"
            }
        }
        
        return ResponseFormatter.success(
            message="系统健康状态正常",
            data=health_status
        )
        
    except Exception as e:
        logger.error(f"健康检查失败: {e}")
        return ResponseFormatter.error(
            message=f"健康检查失败: {str(e)}",
            error_code="HEALTH_CHECK_ERROR"
        )